package simple;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class ConsumerDemo {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        //建立连接
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("139.199.198.28"); //ip 地址
        connectionFactory.setPort(5672); //端口号
        connectionFactory.setUsername("admin"); //用户名
        connectionFactory.setPassword("admin"); //密码
        connectionFactory.setVirtualHost("/"); //虚拟主机
        Connection connection = connectionFactory.newConnection();

        //开启信道
        Channel channel = connection.createChannel();

        //声明交换机，此处使用内置交换机

        //声明队列(若生产者已经声明，可以省略)
        //在消费者启动时，若队列不存在，就会报错
        /**
         * queueDeclare(
         * String queue,  队列名称
         * boolean durable,  可持久化
         * boolean exclusive,  独占
         * boolean autoDelete,  自动删除
         * Map<String, Object> arguments 参数
         * )
         */
        channel.queueDeclare("hello", true, false, false, null);

        //消费消息
        /**
         * basicConsume(
         * String queue, 队列名
         * boolean autoAck,  自动确认
         * Consumer callback //收到消息后，执行的逻辑
         * )
         */
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                //可能还没有来得及打印，资源就已经释放了
                String messageInfo = new String(body);
                System.out.println(messageInfo);
            }
        };
        channel.basicConsume("hello", true, consumer);

        Thread.sleep(1000);

        //资源释放
        //先释放 channel ，后释放 connection
        channel.close();
        connection.close(); // connection 关闭后，包含的 channel 也就关闭了
    }
}
